package com.raft.framework.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import com.raft.framework.utils.AssetUtils;

import java.io.File;

public class DBHelper {

    public static SQLiteDatabase openAssetsDB(Context context,String dbName){
        SQLiteDatabase sqLiteDatabase = null;
        File dbFile = context.getDatabasePath(dbName);
        if (!dbFile.exists()){
            //文件不存在，复制
            AssetUtils.copy(context,dbName,dbFile);
        }
        //打开db
        sqLiteDatabase  = openDB(dbFile.getPath(), false);
        if (sqLiteDatabase == null){
            //打开失败了，再复制一次打开
            AssetUtils.copy(context,dbName,dbFile);
            sqLiteDatabase  = openDB(dbFile.getPath(), false);
        }

        return sqLiteDatabase;
    }


    private static SQLiteDatabase openDB(String path,boolean afterClose){
        SQLiteDatabase checkDB = null;
        try {
            checkDB = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
        } catch (SQLiteException e) {
            //database does't exist yet.
        }

        if (afterClose && checkDB != null) {
            checkDB.close();
            return null;
        }
        return checkDB;
    }

}
